package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.enums.CouponStateEnums;
import one.stand.enums.CouponTypeEnums;
import one.stand.enums.GrantModelEnums;
import one.stand.model.CompanyCouponModel;
import one.stand.model.GoodstypeModel;
import one.stand.model.ResultModel;
import one.stand.model.UserCouponModel;
import one.stand.request.CompanyCouponRequest;
import one.stand.request.CoupponRecordsRequest;
import one.stand.response.CompanyCouponResponse;
import one.stand.response.UserCouponResponse;
import one.stand.service.CompanyCouponService;
import one.stand.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Optional;

/**
 * @author: QIK
 * @CreateDate: 2019/6/24 15:19
 */
@Service
@Transactional
public class CompanyCouponServiceImpl extends PublicBaseService implements CompanyCouponService {
    @Override
    public ResultModel<Boolean> add(CompanyCouponRequest request) {

        CompanyCouponModel companyCouponModel = new CompanyCouponModel();
        BeanUtils.copyProperties(request, companyCouponModel);
        companyCouponModel.setCompanyId(request.getCId());
        companyCouponModel.setCreateTime(DateUtil.now());
        log.info("创建优惠券参数: {}", request);
        int insertRes = companyCouponMapper.insertSelective(companyCouponModel);
        if (insertRes <= 0) {
            return ResultModel.fail();
        }
        return ResultModel.success();
    }

    @Override
    public ResultModel<Boolean> upd(CompanyCouponRequest request,final Long couponId) {
        if (null == request) {
            return ResultModel.checkParamFail();
        }

        CompanyCouponModel companyCouponModel = companyCouponMapper.selectByPrimaryKey(couponId);
        if (null == companyCouponModel) {
            return ResultModel.noData();
        }
//        if (null != request.getEffectiveEndTime()) {
//            if (request.getEffectiveEndTime().getTime() <= companyCouponModel.getEffectiveEndTime().getTime()) {
//                return ResultModel.fail("只能延长有效期！！！");
//            }
//            companyCouponModel.setEffectiveEndTime(request.getEffectiveEndTime());
//        }
//        if (null != request.getGrantEndTime()) {
//            if (request.getGrantEndTime().getTime() <= companyCouponModel.getGrantEndTime().getTime()) {
//                return ResultModel.fail("不能缩短发放截止时间！！！");
//            }
//            companyCouponModel.setGrantEndTime(request.getGrantEndTime());
//        }
        BeanUtils.copyProperties(request, companyCouponModel,"id");
        int updRes = companyCouponMapper.updateByPrimaryKeySelective(companyCouponModel);
        if (updRes <= 0) {
            return ResultModel.fail();
        }
        return ResultModel.success();
    }


    @Override
    public ResultModel<Boolean> updState(final Integer pubState, final Long couponId){
        CompanyCouponModel companyCouponModel = companyCouponMapper.selectByPrimaryKey(couponId);
        if (null == companyCouponModel) {
            return ResultModel.noData();
        }
        companyCouponModel.setPubState(pubState);
        int updRes = companyCouponMapper.updateByPrimaryKeySelective(companyCouponModel);
        if (updRes <= 0) {
            return ResultModel.fail();
        }
        return ResultModel.success();
    }
    @Override
    public ResultModel<CompanyCouponResponse> findCompanyCouponById(CompanyCouponRequest request) {
        if (null == request || request.getCouponId() == null) {
            return ResultModel.checkParamFail();
        }
        CompanyCouponModel companyCouponModel = companyCouponMapper.selectByPrimaryKey(request.getCouponId());
        if (null == companyCouponModel) {
            return ResultModel.noData();
        }
        CompanyCouponResponse response = new CompanyCouponResponse();
        BeanUtils.copyProperties(companyCouponModel, response);
        return ResultModel.success(response);
    }

    @Override
    public ResultModel<Boolean> del(final Long couponId) {
        if (null == couponId) {
            return ResultModel.checkParamFail();
        }
        CompanyCouponModel companyCouponModel = companyCouponMapper.selectByPrimaryKey(couponId);
        if (null == companyCouponModel) {
            return ResultModel.noData();
        }
        if (companyCouponModel.getEffectiveEndTime().getTime() <= currentDate().getTime()) {
            return ResultModel.fail("只能删除过期的优惠券");
        }
        int delRes = companyCouponMapper.deleteByPrimaryKey(couponId);
        if (delRes <= 0) {
            return ResultModel.fail();
        }
        return ResultModel.success();

    }

    @Override
    public ResultModel<PageInfo<CompanyCouponResponse>> crmPcPageList(CompanyCouponRequest request) {
        CompanyCouponModel model = new CompanyCouponModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        log.info("查询优惠券列表参数: {}", JSON.toJSONString(model));
        List<CompanyCouponModel> list = companyCouponMapper.crmPcSelectGoodsTypeList(model);
        List<CompanyCouponResponse> companyCouponResponses = new ArrayList<>(0);
        list.forEach(companyCouponModel -> {
            {
                CompanyCouponResponse response = new CompanyCouponResponse();
                BeanUtils.copyProperties(companyCouponModel, response);
                response.setCouponTypeText(CouponTypeEnums.getName(response.getCouponType()));
                response.setGrantObjectText(response.getGrantObject() == 1 ? "所有对象" : "新用户");
                response.setGrantModeText(GrantModelEnums.getName(response.getGrantMode()));
//                response.setReceiveNumText(response.getReceiveNum() == 0 ? "不限制" : "限制".concat(String.valueOf(response.getReceiveNum())).concat("张"));
                response.setGoodsTypeName(response.getGoodstypeId() == 0 ? "全场通用" : response.getGoodsTypeName());
                //处理商品分类
//                 ,gt.name as goodsTypeName
                if(companyCouponModel.getGoodstypeId() == 0){
                    response.setGoodsTypeName("不限制");
                }else{
                    final GoodstypeModel goodstypeModel = this.goodstypeMapper.selectByPrimaryKey(companyCouponModel.getGoodstypeId());
                    response.setGoodsTypeName(Optional.ofNullable(goodstypeModel).isPresent() ? goodstypeModel.getName() : "");
                }

                companyCouponResponses.add(response);
            }
        });
        PageInfo<CompanyCouponResponse> pageInfo = new PageInfo(companyCouponResponses);
//        //当前条件总数
//        int count = companyCouponMapper.crmPcSelectGoodsTypeListCount(model);
//        pageInfo.setTotal(count);
        return ResultModel.success(pageInfo);
    }

    /**
     * 查询优惠券领取记录
     * @param request
     * @return
     */
    @Override
    public ResultModel<PageInfo<UserCouponResponse>> coupponRecords(CoupponRecordsRequest request) {
        UserCouponModel model = new UserCouponModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId());
        request.setCompanyId(request.getCId());
        log.info("查询优惠券领取记录: {}", JSON.toJSONString(model));
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        request.setCouponState(request.getCouponState() == 0 ? null : request.getCouponState());
        List<UserCouponModel> list = userCouponMapper.coupponRecordsList(request);
        List<UserCouponResponse> userCouponResponses = new ArrayList<>(0);
        list.forEach(userCouponModel -> {
            {
                UserCouponResponse response = new UserCouponResponse();
                BeanUtils.copyProperties(userCouponModel, response);
                response.setNickName(new String(Base64.getDecoder().decode(userCouponModel.getNickName())));
                response.setGrantModeText(GrantModelEnums.getName(response.getGrantMode()));
                response.setCouponStateText(CouponStateEnums.getName(response.getCouponState()));
                userCouponResponses.add(response);
            }
        });
        PageInfo<UserCouponResponse> pageInfo = new PageInfo(userCouponResponses);
        return ResultModel.success(pageInfo);
    }
}
